<?php
namespace app\admin\model;

use think\Model;

class TpGoods extends Model
{
	protected $field=true;
	protected static function init()
	{

		TpGoods::beforeInsert(function ($goods) {
			
			if($_FILES['or_thumb']['tmp_name']){

				$thumbName=$goods->upload('or_thumb');
                $orThumb=date("Ymd"). DS . $thumbName;
                $bigThumb=date("Ymd"). DS . 'big_'.$thumbName;
                $midThumb=date("Ymd"). DS . 'mid_'.$thumbName;
                $smThumb=date("Ymd"). DS . 'sm_'.$thumbName;
                $image = \think\Image::open(IMG_UPLOADS.$orThumb);
                $image->thumb(500, 500,\think\Image::THUMB_CENTER)->save(IMG_UPLOADS.$bigThumb);
                $image->thumb(100, 100)->save(IMG_UPLOADS.$midThumb);
                $image->thumb(50, 50)->save(IMG_UPLOADS.$smThumb);
                $goods->or_thumb=$orThumb;
                $goods->big_thumb=$bigThumb;
                $goods->mid_thumb=$midThumb;
                $goods->sm_thumb=$smThumb;	

            }

			$goods->goods_code=time().rand(111111,999999);//商品编号

		});




        TpGoods::beforeUpdate(function ($goods) {
            $goodsId=$goods->id;

            //处理新增商品属性
            $goodsData=input('post.');
            // dump($goodsData);die;
            
            if(isset($goodsData['goods_attr'])){
                $i=0;
                foreach ($goodsData['goods_attr'] as $k => $v) {
                    if(is_array($v)){
                        if(!empty($v)){
                            foreach ($v as $k1 => $v1) {
                                if(!$v1){
                                    $i++;
                                    continue;
                                }
                                db('tp_goods_attr')->insert(array('attr_id'=>$k,'attr_price'=>$goodsData['attr_price'][$i],'attr_value'=>$v1,'goods_id'=>$goodsId));
                                $i++;
                                
                            }
                        }

                    }else{
                        db('tp_goods_attr')->insert(array('attr_id'=>$k,'attr_value'=>$v,'goods_id'=>$goodsId));
                    }    

                }
            }


            //处理商品推荐位
            if(isset($goodsData['recpos'])){
                db('tp_rec_item')->where(['value_id'=>$goodsId,'value_type'=>1])->delete();
                foreach ($goodsData['recpos'] as $k => $v) {
                    db('tp_rec_item')->insert(['recpos_id'=>$v,'value_id'=>$goodsId,'value_type'=>1]);
                }

            }


            // 商品相册处理
            
            if($goods->_hasImgs($_FILES['goods_photo']['tmp_name'])){
                $files = request()->file('goods_photo');
                foreach($files as $file){
                    // 移动到框架应用根目录/public/uploads/ 目录下
                    $info = $file->move(ROOT_PATH . 'public' . DS .'static'. DS .'uploads');
                    if($info){
                        // 输出 42a79759f284b767dfcb2a0197904287.jpg
                        $photoName=$info->getFilename();
                        $ogphoto=date("Ymd"). DS . $photoName;
                        $bigphoto=date("Ymd"). DS . 'big_'.$photoName;
                        $midphoto=date("Ymd"). DS . 'mid_'.$photoName;
                        $smphoto=date("Ymd"). DS . 'sm_'.$photoName;
                        $image = \think\Image::open(IMG_UPLOADS.$ogphoto);
                        $image->thumb(500, 500)->save(IMG_UPLOADS.$bigphoto);
                        $image->thumb(100, 100)->save(IMG_UPLOADS.$midphoto);
                        $image->thumb(50, 50)->save(IMG_UPLOADS.$smphoto);
                        
                        db('tp_goods_photo')->insert(['goods_id'=>$goodsId,'og_photo'=>$ogphoto,'big_photo'=>$bigphoto,'mid_photo'=>$midphoto,'sm_photo'=>$smphoto]);
                    }else{
                        // 上传失败获取错误信息
                        echo $file->getError();
                    }    
                }
            }


            // 处理会员价格
            $mpriceArr=$goods->mp;
            $mp=db('tp_member_price');
            // 删除原有会员价格
            $mp->where('goods_id','=',$goodsId)->delete();
            // 批量写入会员价格
            if($mpriceArr){
                foreach ($mpriceArr as $k => $v) {
                    if(trim($v) == ''){
                        continue;
                    }else{
                        $mp->insert(['mlevel_id'=>$k,'mprice'=>$v,'goods_id'=>$goodsId]);
                    }
                }
            }



            //修改属性的值
            if(isset($goodsData['old_goods_attr'])){
                $j=0;$l=0;
                foreach ($goodsData['old_goods_attr'] as $k => $v) {
                    if(is_array($v)){
                        if(!empty($v)){
                            foreach ($v as $k1 => $v1) {
                                if(!$v1){
                                    $j++;
                                    continue;
                                }
                                db('tp_goods_attr')->where(array('id'=>$goodsData['old_goods_attrID'][$j]))->update(array('attr_price'=>$goodsData['old_attr_price'][$j],'attr_value'=>$v1));
                                $j++;
                                
                            }
                        }

                    }else{
                        
                        db('tp_goods_attr')->where(array('id'=>$goodsData['old_goods_attrID2'][$l]))->update(array('attr_value'=>$v));
                        $l++;
                    }    

                }
            }





            $goodsThumb=db('tp_goods')->where(array('id'=>$goodsId))->field('or_thumb,big_thumb,mid_thumb,sm_thumb')->select(); 
            if($_FILES['or_thumb']['tmp_name']){
                //上传图片之前如果有旧图片，删除旧图片
                foreach ($goodsThumb as $k => $v) {

                    @unlink(IMG_UPLOADS.$v['or_thumb']);
                    @unlink(IMG_UPLOADS.$v['big_thumb']);
                    @unlink(IMG_UPLOADS.$v['mid_thumb']);
                    @unlink(IMG_UPLOADS.$v['sm_thumb']);

                }

                //上传新的图片
                $thumbName=$goods->upload('or_thumb');
                $orThumb=date("Ymd"). DS . $thumbName;
                $bigThumb=date("Ymd"). DS . 'big_'.$thumbName;
                $midThumb=date("Ymd"). DS . 'mid_'.$thumbName;
                $smThumb=date("Ymd"). DS . 'sm_'.$thumbName;
                $image = \think\Image::open(IMG_UPLOADS.$orThumb);
                $image->thumb(500, 500)->save(IMG_UPLOADS.$bigThumb);
                $image->thumb(100, 100)->save(IMG_UPLOADS.$midThumb);
                $image->thumb(50, 50)->save(IMG_UPLOADS.$smThumb);
                $goods->or_thumb=$orThumb;
                $goods->big_thumb=$bigThumb;
                $goods->mid_thumb=$midThumb;
                $goods->sm_thumb=$smThumb;  

            }          

        });






        TpGoods::afterInsert(function($goods){
			// dump($goods);die;
			// 批量写入会员价格
            $mpriceArr=$goods->mp;
            $goodsId=$goods->id;
            if($mpriceArr){
                foreach ($mpriceArr as $k => $v) {
                    if(trim($v) == ''){
                        continue;
                    }else{
                        db('tp_member_price')->insert(['mlevel_id'=>$k,'mprice'=>$v,'goods_id'=>$goodsId]);
                    }
                }
            }


            //处理商品属性
            $goodsData=input('post.');
            // dump($goodsData);die;
            $i=0;
            if(isset($goodsData['goods_attr'])){
            	foreach ($goodsData['goods_attr'] as $k => $v) {
            		if(is_array($v)){
            			if(!empty($v)){
            				foreach ($v as $k1 => $v1) {
            					if(!$v1){
            						$i++;
            						continue;
            					}
            					db('tp_goods_attr')->insert(array('attr_id'=>$k,'attr_price'=>$goodsData['attr_price'][$i],'attr_value'=>$v1,'goods_id'=>$goodsId));
            					$i++;
            					
            				}
            			}

            		}else{
            			db('tp_goods_attr')->insert(array('attr_id'=>$k,'attr_value'=>$v,'goods_id'=>$goodsId));
            		}


                }
            }

            //处理商品推荐位
            if(isset($goodsData['recpos'])){
                foreach ($goodsData['recpos'] as $k => $v) {
                    db('tp_rec_item')->insert(['recpos_id'=>$v,'value_id'=>$goodsId,'value_type'=>1]);
                }

            }

            // 商品相册处理
            // dump($_FILES); die;
            if($goods->_hasImgs($_FILES['goods_photo']['tmp_name'])){
                $files = request()->file('goods_photo');
                foreach($files as $file){
                    // 移动到框架应用根目录/public/uploads/ 目录下
                    $info = $file->move(ROOT_PATH . 'public' . DS .'static'. DS .'uploads');
                    if($info){
                        // 输出 42a79759f284b767dfcb2a0197904287.jpg
                        $photoName=$info->getFilename();
                        $ogphoto=date("Ymd"). DS . $photoName;
                        $bigphoto=date("Ymd"). DS . 'big_'.$photoName;
                        $midphoto=date("Ymd"). DS . 'mid_'.$photoName;
                        $smphoto=date("Ymd"). DS . 'sm_'.$photoName;
                        $image = \think\Image::open(IMG_UPLOADS.$ogphoto);
                        $image->thumb(500, 500)->save(IMG_UPLOADS.$bigphoto);
                        $image->thumb(100, 100)->save(IMG_UPLOADS.$midphoto);
                        $image->thumb(50, 50)->save(IMG_UPLOADS.$smphoto);
                        
                        db('tp_goods_photo')->insert(['goods_id'=>$goodsId,'og_photo'=>$ogphoto,'big_photo'=>$bigphoto,'mid_photo'=>$midphoto,'sm_photo'=>$smphoto]);
                    }else{
                        // 上传失败获取错误信息
                        echo $file->getError();
                    }    
                }
            }

        });



         TpGoods::beforeDelete(function($goods){
             $goodsId=$goods->id;
             //删除对应推荐位的信息
             db('tp_rec_item')->where(array('value_id'=>$goodsId,'value_type'=>1))->delete();

         });


        


    }


	// 商品相册是否有图片上传判断
    private function _hasImgs($tmpArr){
        foreach ($tmpArr as $k => $v) {
            if($v){
                return true;
            }
        }
        return false;
    }

    public function upload($imgName){
    // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file($imgName);

    // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS .'static'.DS . 'uploads');
            if($info){
            // 成功上传后 获取上传信息
            // 输出 jpg
            // echo $info->getExtension();
            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            // echo $info->getSaveName();
            // 输出 42a79759f284b767dfcb2a0197904287.jpg
                return $info->getFilename(); 
            }else{
            // 上传失败获取错误信息
                echo $file->getError();
            }
        }
    }
}